import config from './config.js'

export const apiResquest = (prams) => {
	return new Promise((resolve, reject) => {
		try {
			uni.showLoading({
				title: '加载中',
				mask: true
			})
			return uni.request({
				url: prams.baseUrl || config.baseUrl + prams.url,
				data: prams.data,
				method: prams.method,
				header: prams.header || {
					'Content-Type': "application/x-www-form-urlencoded",//application/json;charset=utf-8
					"cToken": uni.getStorageSync('cToken'),
					'adminToken': uni.getStorageSync('adminToken'),
					'clanguage':'en-US'
				},
				timeout: prams.timeout || 60000,
				success: (res) => {
					uni.hideLoading()
					console.log(res,"resresres")
					if (res.statusCode == 200) {
						if(res.data?.code == 1002){
							//清空所有信息
							uni.removeStorageSync("cToken");
							uni.showToast({
								title: res.data?.message || res?.message || "会话过期,请重新登录",
								icon: 'none',
								duration: 2000
							});
							const pages = getCurrentPages(); // 获取当前页面栈的数组，数组的第一项为首页，最后一项为当前页面
							const currentPagePath = pages[pages.length - 1].route;
							if(currentPagePath != 'pages/login/login'){
								setTimeout(() => {
									uni.reLaunch({
										url: '/pages/login/login'
									})
								}, 2000)
							}
						}
						else{
							resolve(res.data);
						}
					}
					else{
						uni.showToast({
							title: (res.data?.message || res?.message) || "系统错误,请稍后再试",
							icon: 'none',
							duration: 2000
						})
						reject(res);
					}

				},
				fail: (err) => {
					console.log(err,"errerr")
					if (err.errMsg.includes("timeout")) {
						uni.showToast({
							title: "网络超时,请稍后再试",
							icon: "none",
							duration: 2000
						})
					}
					if (err.errMsg.includes("request:fail") || err.errMsg ==
						'request:fail error') {
						uni.showToast({
							title: "网络连接失败,请稍后再试",
							icon: "none",
							duration: 2000
						})
					}
					reject(err);
					uni.hideLoading()
				},
				complete: () => {
					uni.hideLoading()
				}
			});
		} catch (e) {
			reject(e)
		
		}
	})
}
